package com.quectel.core.module.parkingcard.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.parkingcard.ParkingCardMemberConstants;
import com.quectel.constant.core.parkingcard.ParkingCardMemberDeviceConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.car.service.CarService;
import com.quectel.core.module.carparking.service.CarParkingService;
import com.quectel.core.module.carparking.service.CarParkingSpaceService;
import com.quectel.core.module.parkingcard.dao.ParkingCardMemberDao;
import com.quectel.core.module.parkingcard.dto.ParkingCardMemberDeviceDto;
import com.quectel.core.module.parkingcard.dto.ParkingCardMemberDto;
import com.quectel.core.module.parkingcard.entity.ParkingCardMemberEntity;
import com.quectel.core.module.parkingcard.service.ParkingCardMemberDeviceService;
import com.quectel.core.module.parkingcard.service.ParkingCardMemberService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/04/18 17:23
 */
@DubboService
public class ParkingCardMemberServiceImpl implements ParkingCardMemberService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ParkingCardMemberService.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARKING_CARD_MEMBER_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARKING_CARD_MEMBER_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<ParkingCardMemberDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARKING_CARD_MEMBER_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private ParkingCardMemberDao parkingCardMemberDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private CarParkingService carParkingService;
    @Autowired
    private CarParkingSpaceService carParkingSpaceService;
    @Autowired
    private CarService carService;
    @Autowired
    private ParkingCardMemberDeviceService parkingCardMemberDeviceService;


    @Override
    public ParkingCardMemberDto selectByCarId(Long carId) {
        ParkingCardMemberEntity parkingCardMemberEntity = parkingCardMemberDao.selectOne(new LambdaQueryWrapper<ParkingCardMemberEntity>()
                .eq(ParkingCardMemberEntity::getCarId, carId)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        ParkingCardMemberDto parkingCardMemberDto = CopyUtils.copyObj(parkingCardMemberEntity, ParkingCardMemberDto.class);
        paddingField(parkingCardMemberDto);
        return parkingCardMemberDto;
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.GRID_EVENT_RECORD_LOG_SEQ_INC_LOCK + "#{#dto.villageId}_#{#dto.license}_#{#dto.licenseColor}"
            }
    )
    @Transactional
    public void correct(ParkingCardMemberDto dto) {
        ParkingCardMemberDto newlyDto = new ParkingCardMemberDto();
        newlyDto.setId(dto.getId());
        newlyDto.setDeadline(dto.getDeadline());
        updateById(newlyDto);

        // 存入操作日志
    }

    @Override
    public ParkingCardMemberDto selectValidMember(Long villageId, String license, Byte licenseColor) {
        ParkingCardMemberEntity parkingCardMemberEntity = parkingCardMemberDao.selectOne(new LambdaQueryWrapper<ParkingCardMemberEntity>()
                .eq(ParkingCardMemberEntity::getVillageId, villageId)
                .eq(ParkingCardMemberEntity::getLicense, license)
                .eq(ParkingCardMemberEntity::getLicenseColor, licenseColor)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        if (Objects.nonNull(parkingCardMemberEntity)
                && parkingCardMemberEntity.getDeadline().getTime() > System.currentTimeMillis()
                && ParkingCardMemberConstants.MemberIsFreezeEnum.NO_FREEZE.getFreezeStatus().equals(parkingCardMemberEntity.getIsFreeze())) {
            return CopyUtils.copyObj(parkingCardMemberEntity, ParkingCardMemberDto.class);
        }
        return null;
    }

    @Override
    public ParkingCardMemberDto selectOneMember(Long villageId, String license, Byte licenseColor) {
        ParkingCardMemberEntity parkingCardMemberEntity = parkingCardMemberDao.selectOne(new LambdaQueryWrapper<ParkingCardMemberEntity>()
                .eq(ParkingCardMemberEntity::getVillageId, villageId)
                .eq(ParkingCardMemberEntity::getLicense, license)
                .eq(ParkingCardMemberEntity::getLicenseColor, licenseColor)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        ParkingCardMemberDto parkingCardMemberDto = CopyUtils.copyObj(parkingCardMemberEntity, ParkingCardMemberDto.class);
        paddingField(parkingCardMemberDto);
        return parkingCardMemberDto;
    }

    @Override
    public ParkingCardMemberDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARKING_CARD_MEMBER_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public ParkingCardMemberDto selectById(Long id) {
        ParkingCardMemberEntity entity = parkingCardMemberDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, ParkingCardMemberDto.class));
    }

    @Override
    public List<ParkingCardMemberDto> queryList(Map<String, Object> params) {
        List<ParkingCardMemberEntity> list = parkingCardMemberDao.queryList(params);
        List<ParkingCardMemberDto> result = CopyUtils.copyList(list, ParkingCardMemberDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private ParkingCardMemberDto paddingField(ParkingCardMemberDto dto) {
        long l = System.currentTimeMillis();
        if (dto != null) {
            dto.setVillage(villageService.selectCacheById(dto.getVillageId()));
            dto.setCarParkingSpace(carParkingSpaceService.selectCacheById(dto.getCarParkingSpaceId()));
            dto.setCar(carService.selectCacheById(dto.getCarId()));
            dto.setValid(dto.getDeadline().getTime() > l
                    && ParkingCardMemberConstants.MemberIsFreezeEnum.NO_FREEZE.getFreezeStatus().equals(dto.getIsFreeze()));

            List<ParkingCardMemberDeviceDto> parkingCardMemberDeviceDtos = parkingCardMemberDeviceService.selectByMemberId(dto.getId());
            dto.setParkingCardMemberDeviceDetail(parkingCardMemberDeviceDtos);
            long count = parkingCardMemberDeviceDtos.parallelStream()
                    .filter(o -> !ParkingCardMemberDeviceConstants.StatusEnum.FAILURE.getStatus().equals(o.getStatus()))
                    .count();
            dto.setParkingCardMemberDeviceStatus(String.format("%s/%s", count, parkingCardMemberDeviceDtos.size()));
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return parkingCardMemberDao.queryTotal(params);
    }

    @Override
    public Long save(ParkingCardMemberDto dto) {
        ParkingCardMemberEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberEntity.class);
        entity.setId(Snowflake.nextId());
        parkingCardMemberDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(ParkingCardMemberDto dto) {
        ParkingCardMemberEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberEntity.class);

        parkingCardMemberDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(ParkingCardMemberDto dto) {
        ParkingCardMemberEntity entity = CopyUtils.copyObj(dto, ParkingCardMemberEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, parkingCardMemberDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        parkingCardMemberDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
